export class ChromeStorage {
  // 存储数据
  static async set(key: string, value: any) {
    try {
      await browser.storage.local.set({ [key]: value })
      return true
    } catch (error) {
      console.error('Storage set error:', error)
    }
  }

  // 获取数据
  static async get(key: string) {
    try {
      const result = await browser.storage.local.get(key)
      return result[key]
    } catch (error) {
      console.error('Storage get error:', error)
    }
  }

  // 删除数据
  static async remove(key: string) {
    try {
      await browser.storage.local.remove(key)
      return true
    } catch (error) {
      console.error('Storage remove error:', error)
    }
  }

  // 清空所有数据
  static async clear() {
    try {
      await browser.storage.local.clear()
      return true
    } catch (error) {
      console.error('Storage clear error:', error)
    }
  }

  // 获取所有数据
  static async getAll() {
    try {
      return await browser.storage.local.get(null)
    } catch (error) {
      console.error('Storage getAll error:', error)
    }
  }

  // 批量存储数据
  static async setMultiple(items: string[]) {
    try {
      await browser.storage.local.set(items)
      return true
    } catch (error) {
      console.error('Storage setMultiple error:', error)
    }
  }
}
/**
 * 监听存储变化
 * @param key
 * @param callback
 */
interface StorageParams {
  newValue: any
  oldValue: any
}
export function storageChange(key: string, callback: (values: StorageParams) => void) {
  browser.storage.onChanged.addListener((changes, areaName) => {
    if (areaName === 'local') {
      if (changes[key]) {
        callback?.(changes[key] as StorageParams)
      }
    }
  })
}
